package com.ebelter.bodyfatscale.util;

import android.text.TextUtils;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by ZCQ on 2017/11/27
 */

public class GsonUtils {
    private static GsonUtils instance;
    private GsonUtils(){}

    public static GsonUtils getInstance() {
        if (instance==null){
            synchronized (GsonUtils.class){
                if (instance==null) instance=new GsonUtils();
            }
        }
        return instance;
    }

    private Gson gson;
    public Gson getGson(){
        if (gson==null){
            gson=new Gson();
        }

        return gson;
    }

    public <T> T fromJson(String json, Class<T> classOfT){
        if (TextUtils.isEmpty(json)){
            return null;
        }
        //为了稳定性App特意在此加一条try-catch，防止后台返回的是不规则的数据 坑的是移动端
        try {
            return getGson().fromJson(json,classOfT);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public <T> T fromJson(String json, Class<T> classOfT,Class clz){
        if (TextUtils.isEmpty(json)){
            return null;
        }

        Type objectType = type(classOfT, clz);

        //为了稳定性App特意在此加一条try-catch，防止后台返回的是不规则的数据 坑的是移动端
        try {
            return getGson().fromJson(json,objectType);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    private static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };

    }



}
